package com.xbts.web.controller.cloud;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xbts.common.annotation.Log;
import com.xbts.common.core.controller.BaseController;
import com.xbts.common.core.domain.AjaxResult;
import com.xbts.common.core.page.TableDataInfo;
import com.xbts.common.enums.BusinessType;
import com.xbts.common.enums.ShoppingCarEnums;
import com.xbts.common.utils.StringUtils;
import com.xbts.common.utils.poi.ExcelUtil;
import com.xbts.system.domain.CnArticle;
import com.xbts.system.domain.CnGovernmentCloud;
import com.xbts.system.domain.CnOrderItem;
import com.xbts.system.domain.CnSolution;
import com.xbts.system.domain.vo.SysStatisticsVo;
import com.xbts.system.enums.OrderStatusEnum;
import com.xbts.system.enums.OrderTypeEnum;
import com.xbts.system.service.ICnGovernmentCloudService;
import com.xbts.system.service.ICnOrderItemService;
import com.xbts.system.service.ICnSolutionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 解决方案Controller
 * @author xbts
 * @date 2023-08-03
 */
@Api("后台统计")
@RestController
@RequestMapping("/system/statistics")
public class CnStatisticsController extends BaseController {

    @Autowired
    private ICnOrderItemService orderItemService;

    @Autowired
    private ICnGovernmentCloudService governmentCloudService;

    /**
     * 按产品统计
     */
    @ApiOperation("按产品统计")
    @GetMapping("/byProduct")
    public AjaxResult byProductList(String startTime, String endTime){
        List<SysStatisticsVo> result = getStatisticsByProduct(startTime, endTime);
        return AjaxResult.success(result);
    }

    @NotNull
    private List<SysStatisticsVo> getStatisticsByProduct(String startTime, String endTime) {

        List<CnOrderItem> list = orderItemService.list(new LambdaQueryWrapper<CnOrderItem>()
                .eq(CnOrderItem::getOrderStatus, OrderStatusEnum.SUCCESS)
                .le(StringUtils.isNotBlank(startTime), CnOrderItem::getCreateTime, endTime)
                .ge(StringUtils.isNotBlank(endTime), CnOrderItem::getCreateTime, startTime));
        List<SysStatisticsVo> result = new ArrayList<>();
        List<BigDecimal> cloudMarketList = list.stream().filter(item -> item.getShoppingCarEnums().equals(ShoppingCarEnums.CLOUD_MARKET)).map(CnOrderItem::getUpdatePrice).collect(Collectors.toList());
        List<BigDecimal> govCloudList = list.stream().filter(item -> item.getShoppingCarEnums().equals(ShoppingCarEnums.GOV_CLOUD)).map(CnOrderItem::getUpdatePrice).collect(Collectors.toList());
        List<BigDecimal> cloudServerList = list.stream().filter(item -> item.getShoppingCarEnums().equals(ShoppingCarEnums.CLOUD_SERVER)).map(CnOrderItem::getUpdatePrice).collect(Collectors.toList());
        List<BigDecimal> cloudServeRenewList = list.stream().filter(item -> item.getShoppingCarEnums().equals(ShoppingCarEnums.CLOUD_SERVER_RENEW)).map(CnOrderItem::getUpdatePrice).collect(Collectors.toList());
        List<BigDecimal> cloudServeChangeList = list.stream().filter(item -> item.getShoppingCarEnums().equals(ShoppingCarEnums.CLOUD_SERVER_CHANGE)).map(CnOrderItem::getUpdatePrice).collect(Collectors.toList());

        // 云市场
        SysStatisticsVo cloudMarketVo = new SysStatisticsVo();
        cloudMarketVo.setType("CLOUD_MARKET");
        cloudMarketVo.setCount(cloudMarketList.size());
        cloudMarketVo.setAmount(cloudMarketList.stream().reduce(BigDecimal.ZERO, BigDecimal::add));

        // 政务云
        SysStatisticsVo govCloudVo = new SysStatisticsVo();
        govCloudVo.setType("GOV_CLOUD");
        govCloudVo.setCount(govCloudList.size());
        govCloudVo.setAmount(govCloudList.stream().reduce(BigDecimal.ZERO, BigDecimal::add));

        // 云服务器
        SysStatisticsVo cloudServerVo = new SysStatisticsVo();
        cloudServerVo.setType("CLOUD_SERVER");
        cloudServerVo.setCount(cloudServerList.size() + cloudServeRenewList.size() + cloudServeChangeList.size());
        cloudServerVo.setAmount(cloudServerList.stream().reduce(BigDecimal.ZERO, BigDecimal::add).add(cloudServeRenewList.stream().reduce(BigDecimal.ZERO, BigDecimal::add)).add(cloudServeChangeList.stream().reduce(BigDecimal.ZERO, BigDecimal::add)));

        result.add(cloudMarketVo);
        result.add(govCloudVo);
        result.add(cloudServerVo);

        // 计算各个类型的平均值
        for (SysStatisticsVo sysStatisticsVo : result) {
            if (sysStatisticsVo.getCount() > 0) {
                sysStatisticsVo.setAverage(sysStatisticsVo.getAmount().divide(new BigDecimal(sysStatisticsVo.getCount()), 2, RoundingMode.HALF_UP));
            }
        }
        return result;
    }

    /**
     * 导出按产品统计
     */
    @ApiOperation("导出按产品统计")
    @PostMapping("/byProduct/export")
    public void byProductExport(HttpServletResponse response, String startTime, String endTime) {
        List<SysStatisticsVo> list = getStatisticsByProduct(startTime, endTime);
        ExcelUtil<SysStatisticsVo> util = new ExcelUtil<SysStatisticsVo>(SysStatisticsVo.class);
        util.exportExcel(response, list, "按产品统计数据");
    }

    /**
     * 按分类统计
     */
    @ApiOperation("按产品统计")
    @GetMapping("/byType")
    public AjaxResult byTypeList(String startTime, String endTime){
        Map<String, Object> result = getStatisticsByType(startTime, endTime);
        return AjaxResult.success(result);
    }

    /**
     * 导出按产品统计
     */
    @ApiOperation("导出按产品统计")
    @PostMapping("/byType/export")
    public void byTypeExport(HttpServletResponse response, String startTime, String endTime) {
        List<SysStatisticsVo> list = (List<SysStatisticsVo>) getStatisticsByType(startTime, endTime).get("list");
        ExcelUtil<SysStatisticsVo> util = new ExcelUtil<SysStatisticsVo>(SysStatisticsVo.class);
        util.exportExcel(response, list, "按产品统计数据");
    }

    private Map<String, Object> getStatisticsByType(String startTime, String endTime) {

        Map<String, Object> resultMap = new HashMap<>();

        List<CnOrderItem> list = orderItemService.list(new LambdaQueryWrapper<CnOrderItem>()
                .eq(CnOrderItem::getOrderStatus, OrderStatusEnum.SUCCESS)
                .eq(CnOrderItem::getShoppingCarEnums, ShoppingCarEnums.GOV_CLOUD.name())
                .le(StringUtils.isNotBlank(startTime), CnOrderItem::getCreateTime, endTime)
                .ge(StringUtils.isNotBlank(endTime), CnOrderItem::getCreateTime, startTime));

        List<CnGovernmentCloud> govCloudList = governmentCloudService.list();
        Map<String, CnGovernmentCloud> map = govCloudList.stream().collect(Collectors.toMap(CnGovernmentCloud::getGovId, cnGovernmentCloud -> cnGovernmentCloud));

        List<SysStatisticsVo> resultList = new ArrayList<>();
        SysStatisticsVo cpuVo = new SysStatisticsVo();
        cpuVo.setType("cpu");
        SysStatisticsVo memoryVo = new SysStatisticsVo();
        memoryVo.setType("memory");
        SysStatisticsVo hardDiskVo = new SysStatisticsVo();
        hardDiskVo.setType("hardDisk");
        SysStatisticsVo defenseVo = new SysStatisticsVo();
        defenseVo.setType("defense");
        SysStatisticsVo bandwidthVo = new SysStatisticsVo();
        bandwidthVo.setType("bandwidth");
        SysStatisticsVo ipVo = new SysStatisticsVo();
        ipVo.setType("ip");
        SysStatisticsVo otherVo = new SysStatisticsVo();
        otherVo.setType("other");

        BigDecimal salesVolume = BigDecimal.ZERO;
        for (CnOrderItem orderItem : list) {
            String govId = orderItem.getRelationId();
            salesVolume = salesVolume.add(orderItem.getUpdatePrice());
            if (map.containsKey(govId)) {
                CnGovernmentCloud governmentCloud = map.get(govId);
                boolean use = false;
                if(StringUtils.isNotBlank(governmentCloud.getCpu())){
                    use = true;
                    cpuVo.setCount(cpuVo.getCount() + 1);
                    cpuVo.setAmount(cpuVo.getAmount().add(orderItem.getUpdatePrice()));
                }
                if(StringUtils.isNotBlank(governmentCloud.getMemory())){
                    use = true;
                    memoryVo.setCount(memoryVo.getCount() + 1);
                    memoryVo.setAmount(memoryVo.getAmount().add(orderItem.getUpdatePrice()));
                }
                if(StringUtils.isNotBlank(governmentCloud.getHardDisk())){
                    use = true;
                    hardDiskVo.setCount(hardDiskVo.getCount() + 1);
                    hardDiskVo.setAmount(hardDiskVo.getAmount().add(orderItem.getUpdatePrice()));
                }
                if(StringUtils.isNotBlank(governmentCloud.getDefense())){
                    use = true;
                    defenseVo.setCount(defenseVo.getCount() + 1);
                    defenseVo.setAmount(defenseVo.getAmount().add(orderItem.getUpdatePrice()));
                }
                if(StringUtils.isNotBlank(governmentCloud.getBandwidth())){
                    use = true;
                    bandwidthVo.setCount(bandwidthVo.getCount() + 1);
                    bandwidthVo.setAmount(bandwidthVo.getAmount().add(orderItem.getUpdatePrice()));
                }
                if(StringUtils.isNotBlank(governmentCloud.getIp())){
                    use = true;
                    ipVo.setCount(ipVo.getCount() + 1);
                    ipVo.setAmount(ipVo.getAmount().add(orderItem.getUpdatePrice()));
                }
                if(!use){
                    otherVo.setCount(otherVo.getCount() + 1);
                    otherVo.setAmount(otherVo.getAmount().add(orderItem.getUpdatePrice()));
                }
                use = false;
            } else {
                otherVo.setCount(otherVo.getCount() + 1);
                otherVo.setAmount(otherVo.getAmount().add(orderItem.getUpdatePrice()));
            }
        }
        resultList.add(cpuVo);
        resultList.add(memoryVo);
        resultList.add(hardDiskVo);
        resultList.add(defenseVo);
        resultList.add(bandwidthVo);
        resultList.add(ipVo);
        resultList.add(otherVo);

        // 计算各个类型的平均值
        for (SysStatisticsVo sysStatisticsVo : resultList) {
            if (sysStatisticsVo.getCount() > 0) {
                sysStatisticsVo.setAverage(sysStatisticsVo.getAmount().divide(new BigDecimal(sysStatisticsVo.getCount()), 2, RoundingMode.HALF_UP));
            }
        }
        resultMap.put("list", resultList);
        resultMap.put("total", list.size());
        resultMap.put("salesVolume", salesVolume);
        return resultMap;
    }
}